import React, { useRef, useEffect } from 'react';
import {PageContainer} from '@ant-design/pro-components';
import * as THREE from 'three';

const  RotatingCube =() => {
  const mountRef = useRef(null);

  useEffect(() => {
    // 1. 初始化场景
    const scene = new THREE.Scene();
    
    // 2. 初始化相机（透视相机）
    const camera = new THREE.PerspectiveCamera(
      75 , // 视野角度
     1/1, // 宽高比
      0.1, // 近裁剪面
      1000 // 远裁剪面
    );
    camera.position.z = 2; // 将相机向后移动
    
    // 3. 初始化渲染器
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(300, 300);
    mountRef.current?.appendChild(renderer.domElement);
    
    // 4. 创建立方体
    const geometry = new THREE.BoxGeometry(1, 1, 1); // 立方体几何体
    const material = new THREE.MeshBasicMaterial({ color: 'red' }); // 绿色材质
    const cube = new THREE.Mesh(geometry, material); // 创建网格对象
    scene.add(cube); // 将立方体添加到场景中
    
    // 5. 动画循环
    const animate = () => {
      requestAnimationFrame(animate);
      
      // 旋转立方体
      cube.rotation.x += 0.01;
      cube.rotation.y += 0.01;
      
      renderer.render(scene, camera);
    };
    
    animate();
    
    // 6. 处理窗口大小变化
    const handleResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };
    
    window.addEventListener('resize', handleResize);
    
    // 7. 组件卸载时清理
    return () => {
      window.removeEventListener('resize', handleResize);
      mountRef.current?.removeChild(renderer.domElement);
    };
  }, []);

  return(
    <PageContainer header={{breadcrumb:undefined, title: 'Three.js 示例'}}>
      <div ref={mountRef} style={{ width: '100%'}} />
    </PageContainer>
  ) 
}

export default RotatingCube;